package cn.hchaojie.javase.day15;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.junit.Test;

// Reader -> 字符流
// Stream -> 字节流


// 读文本文件，使用字符流
// 读中文的时候，一个char有可能放不下一个中文
public class DemoReaderWriter {
	@Test
	public void testReader() {
		try (
			Reader reader = new InputStreamReader(new FileInputStream("中文测试文件.txt"), "gbk");
				) {
			
			char[] chars = new char[1024];
			int count = reader.read(chars);
			
			System.out.println(new String(chars, 0, count));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testReader2() {
		Reader reader;
		try {
			reader = new FileReader("中文测试文件.txt");
			char[] chars = new char[1024];
			
			int count = reader.read(chars);
			System.out.println(new String(chars, 0, count));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// 使用缓冲流复制文件
	@Test
	public void testBufferedReader() {
		String source = "三国演义.txt";
		String target = "三国演义2.txt";
		
		// 装饰者模式
		try (
			BufferedReader reader = new BufferedReader(new FileReader(source));
			BufferedWriter writer = new BufferedWriter(new FileWriter(target));
				) {
			String line = null;
			
			// reader.read();
			while ((line = reader.readLine()) != null) {
				writer.write(line);
				writer.write("\n");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
